package utils

import (
	"bytes"
	"crypto/aes"
	cipher2 "crypto/cipher"
	"crypto/md5"
	"errors"
	"fmt"
)

func Md5Crypto(s string) string {
	hash := md5.New()
	hash.Write([]byte(s))
	return fmt.Sprintf("%x", hash.Sum(nil))
}

type AES struct {
	Data string `json:"data"`
	Key  string `json:"key"`
}

func (r *AES) AESEncrypt() (string, error) {
	cipher, err := aes.NewCipher([]byte(r.Key))
	if err != nil {
		return "", err
	}
	blockSize := cipher.BlockSize()
	padding := blockSize - len(r.Data)%blockSize
	if padding == 0 {
		padding = blockSize
	}
	paddingData := append([]byte(r.Data), bytes.Repeat([]byte{byte(padding)}, padding)...)
	// 创建 CBC 分组模式加密器
	iv := make([]byte, blockSize)
	stream := cipher2.NewCBCDecrypter(cipher, iv)
	// 加密数据
	encryptedData := make([]byte, len(paddingData))
	stream.CryptBlocks(encryptedData, paddingData)
	return fmt.Sprintf("%x", encryptedData), nil
}
func (r *AES) AESDecrypt() (string, error) {
	// 创建 AES 加密器
	block, err := aes.NewCipher([]byte(r.Key))
	if err != nil {
		return "", err
	}

	// 创建 CBC 分组模式解密器
	iv := make([]byte, block.BlockSize())
	stream := cipher2.NewCBCDecrypter(block, iv)

	// 解密数据
	decryptedData := make([]byte, len(r.Data))
	stream.CryptBlocks(decryptedData, []byte(r.Data))

	// 对解密后的数据进行去填充
	padding := int(decryptedData[len(decryptedData)-1])
	if padding < 1 || padding > block.BlockSize() {
		return "", errors.New("invalid padding")
	}
	return fmt.Sprintf("%x", decryptedData[:len(decryptedData)-padding]), nil
}
